package com.beiing.tianshuai.tianshuai.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.DemoCache;
import com.beiing.tianshuai.tianshuai.entity.IsBindingBean;
import com.beiing.tianshuai.tianshuai.mine.ui.BindingActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.nim.config.preference.Preferences;
import com.beiing.tianshuai.tianshuai.nim.config.preference.UserPreferences;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.wxapi.bean.WeChatBean;
import com.beiing.tianshuai.tianshuai.wxapi.bean.WeChatUserInfoBean;
import com.mic.etoast2.Toast;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.net.URLEncoder;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";
    private Context mContext;
    private IWXAPI api;

    /**
     * 获取第一步的code后，请求以下链接获取access_token
     */
    private String getCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    /**
     * 获取用户个人信息
     */
    private String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        api = WXAPIFactory.createWXAPI(this, AppConstant.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    /**
     * 微信发送请求到第三方应用时，会回调到该方法
     */
    @Override
    public void onReq(BaseReq req) {
        finish();
    }

    /**
     * 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
     */
    @Override
    public void onResp(BaseResp resp) {
        String result;
        if (resp == null) {
            return;
        }
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    //登录回调，处理登录成功后的逻辑
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        //登录成功
                        String code = ((SendAuth.Resp) resp).code;
                        /*
                         * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
                         */
                        String getAccessToken = getCodeRequest(code);
                        getRequestInfo(getAccessToken);
                        LogUtil.i(TAG, "登录成功" + getAccessToken);
                        finish();
                        break;
                    //分享回调，处理分享成功后的逻辑
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        result = "分享成功";
                        Toast.makeText(this, result, 1).show();
                        LogUtil.i(TAG, "登录回调" + resp.getType() + result);
                        finish();
                        break;
                    default:
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "已取消操作";
                Toast.makeText(this, result, 1).show();
                LogUtil.i(TAG, result);

                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "登录失败";
                Toast.makeText(this, result, 1).show();
                LogUtil.i(TAG, result);

                finish();
                break;
            default:
                result = "发送返回";
                Toast.makeText(this, result, 1).show();
                LogUtil.i(TAG, result);

                finish();
                break;
        }
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param userInfoUrl 获取用户信息地址
     */
    private void getUserInfo(String userInfoUrl) {
        DisposableObserver<WeChatUserInfoBean> observer = new DisposableObserver<WeChatUserInfoBean>() {
            @Override
            public void onNext(@NonNull WeChatUserInfoBean bean) {
                String unionId = bean.getUnionid();
                if (!TextUtils.isEmpty(unionId)) {
                    isBinding(unionId, bean);
                    LogUtils.i(bean.toString(), "微信用户信息2");
                } else {
                    Toast.makeText(mContext, "登录失败", 0).show();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getWeChatUserInfo(userInfoUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result;
        getCodeRequest = getCodeRequest.replace("APPID", urlEnCodeUTF8(AppConstant.WX_APP_ID));
        getCodeRequest = getCodeRequest.replace("SECRET", urlEnCodeUTF8(AppConstant.WX_APP_SECRET));
        getCodeRequest = getCodeRequest.replace("CODE", urlEnCodeUTF8(code));
        result = getCodeRequest;
        LogUtil.i(TAG, "微信回调" + urlEnCodeUTF8(AppConstant.WX_APP_ID) + " " + urlEnCodeUTF8(AppConstant.WX_APP_SECRET) +
                " " + urlEnCodeUTF8(code));
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param accessToken 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String accessToken, String openid) {
        String result;
        getUserInfo = getUserInfo.replace("ACCESS_TOKEN", urlEnCodeUTF8(accessToken));
        getUserInfo = getUserInfo.replace("OPENID", urlEnCodeUTF8(openid));
        result = getUserInfo;
        return result;
    }

    private String urlEnCodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void getRequestInfo(String getAccessToken) {
        DisposableObserver<WeChatBean> observer = new DisposableObserver<WeChatBean>() {
            @Override
            public void onNext(@NonNull WeChatBean bean) {
                String accessToken = bean.getAccessToken();
                String openid = bean.getOpenid();
                String getUserInfoUrl = getUserInfo(
                        accessToken, openid);
                getUserInfo(getUserInfoUrl);
                LogUtils.i(bean.toString(), "微信用户信息1");
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getWeChatRequestResult(getAccessToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 判断用户是否绑定手机号码
     *
     * @param unionId      用户唯一标识
     * @param userInfoBean 用户信息
     */
    private void isBinding(final String unionId, final WeChatUserInfoBean userInfoBean) {
        DisposableObserver<IsBindingBean> observer = new DisposableObserver<IsBindingBean>() {
            @Override
            public void onNext(@NonNull IsBindingBean bean) {
                int code = bean.getCode();
                switch (code) {
                    case 200:
                        IsBindingBean.DataBean.NumberBean userBean = bean.getData().getNumber();
                        SPUtils.put(mContext, "uid", userBean.getUid());
                        SPUtils.put(mContext, "sex", userBean.getSex());
                        SPUtils.put(mContext, "photo", userBean.getPhoto());
                        SPUtils.put(mContext, "tel", userBean.getTel());
                        SPUtils.put(mContext, "status", userBean.getStatus());
                        SPUtils.put(mContext, "name", userBean.getName());
                        SPUtils.put(mContext, "email", userBean.getEmail());
                        SPUtils.put(mContext, "unit", userBean.getUnit());
                        SPUtils.put(mContext, "identification_status", userBean.getAttestaction());
                        SPUtils.put(mContext, "token", userBean.getToken());
                        // 设置极光推送别名
                        JPushInterface.setAlias(mContext, AppConstant.MSG_SET_ALIAS, userBean.getUid());
                        // 登陆网易云信
                        LoginInfo loginInfo = new LoginInfo(userBean.getUid(), userBean.getToken());
                        NimUIKit.login(loginInfo, new RequestCallback<LoginInfo>() {
                            @Override
                            public void onSuccess(LoginInfo loginInfo) {
                                DemoCache.setAccount(loginInfo.getAccount());
                                saveLoginInfo(loginInfo.getAccount(), loginInfo.getToken());
                                // 初始化消息提醒配置
                                initNotificationConfig();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                finish();
                            }

                            @Override
                            public void onFailed(int i) {

                            }

                            @Override
                            public void onException(Throwable throwable) {

                            }
                        });
                        break;
                    case 400:
                        Intent binding = new Intent(mContext, BindingActivity.class);
                        binding.putExtra("unionId", unionId);
                        binding.putExtra("nickName", userInfoBean.getNickname());
                        binding.putExtra("avatarUrl", userInfoBean.getHeadimgurl());
                        binding.putExtra("platform", "wetch");
                        startActivity(binding);
                        break;
                    default:
                        Toast.makeText(WXEntryActivity.this, "登录异常", 0).show();
                        LogUtils.i(TAG, "登录异常");
                        break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.e(e.getMessage(), TAG);
            }

            @Override
            public void onComplete() {
                CustomProgressDialog.stopLoading();
            }
        };

        DataManager.isBinding(unionId, "wetch")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = DemoCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }
}